<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 设备管理 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <!-- <el-cascader :options='options' filterable v-model='op.options' class='handle-input mr10'></el-cascader> -->
                <el-input style="width: 250px" v-model="query.cgText" placeholder="输入关键字" class="handle-input mr10"
                    clearable>
                </el-input>
                <el-select v-model="query.taskStatus" placeholder="设备状态" clearable size="small" style="width: 240px">
                    <el-option v-for="dict in options1.taskStatus" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
                <el-button type="primary" icon="el-icon-search" style="margin-left: 8px" size="mini" @click="search">搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                <el-button type='primary' icon='el-icon-plus' size="mini" class='handle-del mr10' @click='handingAdd'>新增
                </el-button>
            </div>
            <el-table v-loading="loading" :data="process.generalWorld" border class="table" ref="multipleTable"
                header-cell-class-name="table-header">
                <el-table-column label="序号" type="index" align="center" width="50"> </el-table-column>
                <el-table-column prop="name" label="设备名" align="center"></el-table-column>
                <el-table-column prop="type" label="设备类型" align="center"></el-table-column>
                <el-table-column prop="buy_date" label="入库时间" align="center"></el-table-column>

                <el-table-column prop="nick_name" label="购买人" align="center"></el-table-column>
                <el-table-column prop="state" label="状态" align="center">
                    <template slot-scope="scope">
                        <span>{{ formatStatus(scope.row.state) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="lab_name" label="所属实验室" align="center"> </el-table-column>
                <el-table-column prop="remark" label="描述" align="center"></el-table-column>
                <el-table-column label="操作" align="center" width="350">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑 </el-button>
                        <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row, scope.$index)"
                            v-if="scope.row.state!=3">删除 </el-button>
                        <el-button type="text" icon="el-icon-check" @click="handleReturn(scope.row)"
                            v-if="scope.row.state!=0">手动归还 </el-button>
                        <el-button type="text" icon="el-icon-message" @click="watchImage(scope.row)">查看照片 </el-button>
                    </template>
                </el-table-column>
                <!--                <el-table-column prop="status" label="状态" align="center">-->
                <!--                    <template slot-scope="scope">-->
                <!--                        <span>{{ formatStatus(scope.row.status) }}</span>-->
                <!--                    </template>-->
                <!--                </el-table-column>-->
            </el-table>
            <div style="text-align: center">
                <el-pagination background layout="total,sizes,prev, pager, next,jumper"
                    :current-page="pageInfo.currentPage" :page-size="pageInfo.pageSize" :total="pageInfo.pageTotal"
                    :page-sizes="[5, 10, 20, 50]" @size-change="handleSizeChange" @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </div>

        <!--添加页面-->
        <el-dialog :title="this.title" :visible.sync="addVisible" width="600px" append-to-body>
            <div style=" min-height: 480px; font-size: 12px" class="equip">
                <el-form ref="equip" :model="equip" label-width="80px" class="test">
                    <el-form-item label="设备名" prop="name">
                        <el-input v-model="equip.name" placeholder="请输入设备名" style="width: 90%"></el-input>
                    </el-form-item>

                    <el-form-item label="设备类型" prop="type">
                        <el-input v-model="equip.type" placeholder="请输入设备类型" style="width: 90%"></el-input>
                    </el-form-item>
                    <el-form-item label="入库时间" prop="buy_date">
                        <div>
                            <el-date-picker v-model="equip.buy_date" type="date" placeholder="选择日期时间" style="width: 90%"
                                :disabled=this.canable>
                            </el-date-picker>
                        </div>
                    </el-form-item>

                    <!--                    <el-form-item label="购买人" prop="nick_name" >-->
                    <!--                        <el-input v-model="equip.nick_name" placeholder="无需输入默认为当前登录人" style="width: 90%" :disabled="true"></el-input>-->
                    <!--                    </el-form-item>-->
                    <el-form-item label="设备状态" prop="state">
                        <el-select v-model="equip.state" placeholder="请选择状态" :disabled=this.canable style="width: 90%">
                            <el-option label="未借用" value="0"></el-option>
                            <el-option label="已借用" value="1"></el-option>
                            <el-option label="损坏" value="2"></el-option>
                            <el-option label="超时未归还" value="3"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属实验室" prop="lab_name">
                        <el-select v-model="equip.lab_id" placeholder="请选择实验室" style="width: 90%">
                            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="描述" prop="remark">
                        <el-input type="textarea" v-model="equip.remark" style="width: 90%"></el-input>
                    </el-form-item>
                    <el-form-item label="附件上传" prop="">
                        <!-- <el-button @click="" icon="el-icon-message" type="test">上传照片</el-button> -->
                        <el-upload action="https://jsonplaceholder.typicode.com/posts/" accept="image/*"
                            :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" multiple
                            :limit="3" :on-exceed="handleExceed" :file-list="fileList">
                            <el-button @click="" icon="el-icon-message" type="test">上传照片</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </div>
            <div style='text-align: right;margin-top: 20px;'>
                <el-button type="primary" @click="passAdd">确定</el-button>
                <el-button @click="remove">取消</el-button>
            </div>
        </el-dialog>

        <!-- 照片弹窗 -->
        <el-dialog title="设备照片" :visible.sync="dialogImage" width="30%" class="imageDialog">
            <el-image style="width: 100%; height: 300px" :src="url" :preview-src-list="srcList">
            </el-image>
            <span slot="footer">
                <el-button @click="dialogImage = false">取 消</el-button>
                <el-button type="primary" @click="dialogImage = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { parseTime } from '../../utils/common';
import variable from '../../utils/request';
import { getInfo } from '@/api/login';

export default {
    name: 'equip',
    data() {
        return {
            fileList: [],
            srcList: [],
            url: "",
            dialogImage: false,
            options: [],
            options1: {
                taskStatus: [
                    {
                        label: '未借用',
                        value: '0'
                    },
                    {
                        label: '已借用',
                        value: '1'
                    },
                    {
                        label: '损坏',
                        value: '2'
                    },
                    {
                        label: '超时未归还',
                        value: '3',
                    }
                ]
            },
            query: {
                cgText: '',
                taskStatus: undefined
            },
            process: {
                generalWorld: []
            },
            look: {
                cgId: '',
                cgText: ''
            },
            // add:{
            //     cgText:''
            // },
            equip: {
                deptId: ''
            },
            equips: {},
            title: '添加设备',
            clickType: '',
            value: '',
            pageInfo: {
                currentPage: 1,
                pageSize: 10,
                pageTotal: 80
            },

            processId: '',
            tableData: [],
            handingData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            TransferVisible: false,
            lookVisible: false,
            addVisible: false,

            pageTotal: 0,
            idx: -1,
            id: -1,
            password2: '',
            dis: true,
            collectInfo: {},
            transferLsit: [],
            mark: '2',
            loading: true,
            canable: false,
        };
    },
    created() {
        getInfo().then((res) => {
            console.log("id" + res.data.user.userId);
            localStorage.setItem("user_id", res.data.user.userId)
        });
        this.processGeneralData();
        this.dept();
    },
    methods: {
        //上传文件
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(11111, file);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        //查看照片
        watchImage(row) {
            this.dialogImage = true;
            console.log(row);
            //假设照片路径字段为urlList['',';','']
            // this.url = row.urlList[0];
            // this.srcList.row.urlList;
            const url = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.jj20.com%2Fup%2Fallimg%2F1111%2F0R11Q22326%2F1PR1122326-6.jpg&refer=http%3A%2F%2Fpic.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666430544&t=c093fab6dd4e5692f12628beb388aa2b"
            this.url = url;
            this.srcList.push(url);
        },
        //设备列表
        processGeneralData() {
            this.loading = true;
            let json = {
                deptid: '',
                state: this.query.taskStatus,
                mark: this.mark,
                keywords: this.query.cgText,
                pageSize: this.pageInfo.pageSize,
                pageNum: this.pageInfo.currentPage
            };
            console.log(json);
            variable.getaxiosPost('/equip/selectEquipList', json).then((res) => {
                console.log(res);
                if (res.data) {
                    this.pageInfo.pageTotal = res.data.total;
                    this.process.generalWorld = res.data.list;
                }
                this.loading = false;
            });
        },
        // 表单重置
        resetQuery() {
            this.query = {};
            this.processGeneralData();
        },
        //搜索
        search() {
            this.processGeneralData();
        },
        //获取实验室
        dept() {
            let data = {
                dept_id: ''
            };
            variable.getaxiosPost('/laboratory/findAll', data).then((res) => {
                console.log(res.data);
                this.options = res.data.list;
                console.log(this.options);
            });
        },
        // 状态过滤
        formatStatus(val) {
            return val == 0 ? '未借用' : val == 1 ? '已借用' : val == 2 ? '损坏' : val == 3 ? '超时未归还' : '';
        },
        //时间转换

        formatData(row, column, cellValue, index) {
            var s = new Date(cellValue);
            var time = variable.dateFormat(s);
            return time;
        },

        //取消弹框
        remove() {
            console.log(this.equip);
            this.equip = this.equips;
            this.addVisible = false;
        },
        //搜索
        // search(){
        //     this.pageInfo.currentPage = 1
        //     this.processGeneralData()
        // },

        //流转记录

        // 修改操作
        handleEdit(row) {
            this.addVisible = true;
            this.canable = true;
            console.log(row);
            this.title = '设备详情';
            this.clickType = 'update';
            this.equip = JSON.parse(JSON.stringify(row));
            this.equip.state = row.state;
            console.log(this.equip);
            this.equip.deptid = parseInt(row.deptid);
        },
        // 添加操作
        handingAdd() {
            this.addVisible = true;
            this.title = '添加设备信息';
            this.clickType = 'add';
            console.log(this.equip);
            this.equip = this.equips;
            this.canable = false;
        },
        //添加
        addEquip() {
            this.$refs.equip.validate((valid, value, callback) => {
                if (valid) {
                    // valid是一个布尔值通过为true错误为false
                    // 验证通过
                    let data = {
                        id: '',
                        buyDate: parseTime(this.equip.buy_date, '{y}-{m}-{d}'),
                        // buyDate: parseTime(this.equip.buy_date, '{y}-{m}-{d} {h}:{i}:{s}'),
                        //reportTime: this.equip.reportTime,
                        name: this.equip.name,
                        remark: this.equip.remark,
                        state: this.equip.state,
                        labId: this.equip.lab_id,
                        type: this.equip.type,
                        userId: localStorage.getItem("user_id"),
                    };
                    console.log(data);
                    variable.getaxiosPost('/equip/addEquip', data).then((res) => {
                        if (res.code == '0') {
                            this.$message.success('添加成功', {
                                duration: 2000
                            });
                            this.processGeneralData();
                        } else {
                            this.$message.error(res.data.message, {
                                duration: 2000
                            });
                        }
                    });
                } else {
                    // 验证不通过
                    callback(new Error(value + '格式不正确'));
                    return false;
                }
            });
        },
        //修改
        updateequip() {
            let data = {
                id: this.equip.id,
                buyDate: parseTime(this.equip.buy_date, '{y}-{m}-{d}'),
                // buyDate: parseTime(this.equip.buy_date, '{y}-{m}-{d} {h}:{i}:{s}'),
                name: this.equip.name,
                remark: this.equip.remark,
                state: this.equip.state,
                labId: this.equip.lab_id,
                type: this.equip.type,
                // attachment:this.equip.attachment
            };
            console.log(data);
            variable.getaxiosPost('/equip/modifyEquip', data).then((res) => {
                if (res.code == '0') {
                    this.$message.success('修改成功', {
                        duration: 2000
                    });
                    this.processGeneralData();
                } else {
                    this.$message.error(res.data.message, {
                        duration: 2000
                    });
                }
            });
        },

        //提交
        passAdd() {
            console.log(this.clickType);
            if (this.clickType == 'add') {
                //添加
                this.addEquip();
                this.addVisible = false;
            } else if (this.clickType == 'update') {
                //修改
                this.updateequip();
                this.addVisible = false;
                //深拷贝
                //this.processGeneralData();
            }
        },
        //删除
        handleDelete(row, index) {
            console.log(row.id);
            let json = {
                id: row.id
            };
            console.log(json);
            // console.log(index)
            this.$confirm('是否确定要删除此记录', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    variable.getaxiosPost('/equip/delEquip', json).then((res) => {
                        console.log(res);
                        if (res.code == '0') {
                            this.$message.success('删除成功', {
                                duration: 2000
                            });
                            this.processGeneralData();
                        } else {
                            this.$message.error(res.data.message, {
                                duration: 2000
                            });
                        }
                    });
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
        },

        //确定修改
        passUpdate(cgId, cgText) {
            let json = {
                cgId: cgId,
                cgText: cgText
            };
            console.log(json);
            variable.getaxiosPsot('/collect/updatecolectGenearlWord', json).then((res) => {
                console.log(res);
                this.editVisible = false;
                this.processGeneralData();
            });
        },

        // 保存编辑
        saveEdit() {
            this.editVisible = false;
            this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            this.$set(this.tableData, this.idx, this.form);
        },
        /**
         * 分页大小切换
         */
        handleSizeChange(val) {
            this.pageInfo.pageSize = val;
            this.processGeneralData();
        },
        /**
         * 分页切换
         */
        handleCurrentChange(val) {
            console.log(val);
            this.pageInfo.currentPage = val;
            this.processGeneralData();
        },
        //新增
        add() {
            this.editVisible = true;
        },

        // 手动归还
        handleReturn(row) {
            console.log(row.id);
            let json = {
                id: row.id
            };
            console.log(json);
            this.$confirm('是否确定要手动归还', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    variable.getaxiosPost('/equip/returnEquip', json).then((res) => {
                        console.log(res);
                        if (res.code == '0') {
                            this.$message.success('手动归还成功', {
                                duration: 2000
                            });
                            this.processGeneralData();
                        } else {
                            this.$message.error(res.data.message, {
                                duration: 2000
                            });
                        }
                    });

                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消手动归还'
                    });
                });
        }
    }
};
</script>

<style scoped lang="scss">
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

::v-deep .equip .el-form .el-form-item .el-form-item__label {
    width: 100px !important;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}

.imageDialog {
    ::v-deep .el-dialog__body {
        padding: 10px;
        padding-bottom: 0 !important;
    }
}

::v-deep .el-upload {
    width: 21%;
    height: 32px;
}

::v-deep .el-upload--text {
    border: none;
}
</style>
